package cn.myzqu.sign.user.server.service.impl;


import cn.myzqu.sign.user.server.dao.OsAccountMapper;
import cn.myzqu.sign.user.server.dao.OsUserMapper;
import cn.myzqu.sign.user.server.entity.OsAccount;
import cn.myzqu.sign.user.server.entity.OsUser;
import cn.myzqu.sign.user.server.service.AccountService;
import cn.myzqu.sign.user.server.utils.KeyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author: 的川
 * @Date: 2018/12/25.
 */
@Service
public class AccountServiceImpl implements AccountService {



    @Autowired
    private OsAccountMapper accountMapper;

    @Autowired
    private OsUserMapper osUserMapper;


    /**
     * 根据openId查询账号
     * @param openId
     * @return
     */
    @Override
    public OsAccount selectByOpenId(String openId){
        return accountMapper.selectByOpenId(openId);
    }

    /**
     * 微信注册
     * @param osUser
     * @return
     */
    @Override
    @Transactional
    public OsAccount register(OsUser osUser){
        //用户昵称
        if(osUser.getNickName()==null){
            osUser.setNickName("用户"+ KeyUtil.getRandomCode(6));
        }
        //创建时间
        osUser.setRegisterTime(new Date());
        osUser.setUpdateTime(new Date());
        if(osUserMapper.insert(osUser)>0){
            OsAccount osAccount = new OsAccount();
            //默认状态
            osAccount.setId(osUser.getId()+"");
            BeanUtils.copyProperties(osUser,osAccount);
            osAccount.setStatus((byte)0);
            osAccount.setOpenId(osUser.getOpenId());
            if(accountMapper.insert(osAccount)>0){
                return osAccount;
            }
        }
        return null;
    }


}
